/*
 * @Author: GuitarXiaohe && 2205227953@qq.com
 * @Date: 2024-01-22 09:11:54
 * @LastEditors: 18163104359 2205227953@qq.com
 * @LastEditTime: 2024-01-26 17:45:08
 * @FilePath: /umi/src/layouts/index.jsx
 * @Description:
 * QQ:2205227953,邮箱:2205227953@qq.com
 * Copyright (c) 2024 by GuitarXiaohe, All Rights Reserved.
 */
import { history, useLocation, connect, useSelectedRoutes, useAppData } from "umi";
import LogoPage from "../Logo";
import { useEffect, useState } from "react";
import "./index.less";
import { Menu, Layout, theme } from "antd";
const { Sider } = Layout;

// 侧边栏
const SiderMenu = (props) => {
  const suerAppdata = useAppData();
  const r = useSelectedRoutes();
  const { appConfig, dispatch } = props;
  const [openKeys, setOpenKeys] = useState(r.map((t) => t.pathname));
  const location = useLocation();

  // 默认选中展开菜单keys
  const defaultOpenKeys = r.map((t) => t.pathname).pop();

  // 目前所有的最上级目录
  const rootSubmenuKeys = suerAppdata.clientRoutes[0].children
    .filter((t) => t.menuType == "M")
    .map((t) => t.path);

  // 默认选中
  const defautKeys = (val, type = false) => {
    if (val) {
      if (val == "/index") {
        dispatch({
          type: "appConfig/setMenuKey",
          payload: "/index",
        });
      }
      // dispatch({
      //   type: "appConfig/setCollapsed",
      //   payload: val.key == "/index",
      // });

      return;
    }

    if (r[r.length - 1]?.route?.activeMenu) {
      dispatch({
        type: "appConfig/setMenuKey",
        payload: r[r.length - 1].route?.activeMenu,
      });
    } else {
      dispatch({
        type: "appConfig/setMenuKey",
        payload: location.pathname,
      });
    }
  };

  // 菜单点击
  const menuClick = (val) => {
    dispatch({
      type: "appConfig/setCollapsed",
      payload: val.key == "/index",
    });
    history.push(val.key);
  };

  // 展开目录时
  const onOpenChange = (keys) => {
    const latestOpenKey = keys.find((key) => openKeys.indexOf(key) === -1);
    if (latestOpenKey && rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
      setOpenKeys(keys);
    } else {
      setOpenKeys(latestOpenKey ? [latestOpenKey] : []);
    }
  };

  useEffect(() => {
    defautKeys();
  }, []);

  return (
    <Sider
      collapsible
      collapsed={appConfig.collapsed}
      theme={appConfig.siderMenuTheme}
      onCollapse={() => {
        dispatch({
          type: "appConfig/setCollapsed",
          payload: !appConfig.collapsed,
        });
      }}
    >
      <LogoPage />
      <Menu
        theme={appConfig.siderMenuTheme}
        defaultOpenKeys={[defaultOpenKeys]}
        selectedKeys={[appConfig.menuKey]}
        // openKeys={appConfig.menuOpenKey}
        openKeys={openKeys}
        mode="inline"
        onOpenChange={onOpenChange}
        onClick={menuClick}
        items={appConfig.siderMenu}
      />
    </Sider>
  );
};

export default connect((state) => ({ appConfig: state.appConfig }))(SiderMenu);
